package com.chat.api.web.service;


import com.chat.api.utils.PdfUtil;
import com.chat.api.utils.ResultUtil;
import com.chat.api.utils.util.DateUtil;
import com.chat.api.web.po.BlogBean;
import com.chat.api.web.vo.BlogEntity;
import com.chat.api.web.vo.MessageEntity;
import com.chat.api.web.vo.MomentDataEntity;
import com.google.common.collect.Lists;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Service
public class MomentDataService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private BlogService blogService;


    /**
     * 获取在线人数及全国分布情况
     *
     * @param request
     * @return
     */
    public MessageEntity getOnlineReader(HttpServletRequest request) {
        try {
            List<MomentDataEntity> datas = Lists.newArrayList();
            Set<String> keys = redisTemplate.keys("session*");
            for (String key : keys) {
                MomentDataEntity entity = new MomentDataEntity();
                String city = (String) redisTemplate.opsForValue().get(key);
                if (city.equals("全国")) continue;
                entity.setName(city);
                Integer count = 1;
                for (MomentDataEntity data : datas) {
                    if (data.getName().equals(city)) {
                        count++;
                    }
                }
                entity.setCount(1);
                datas.add(entity);
            }
            return ResultUtil.success(datas);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.fail("系统繁忙，请稍后再试");
        }
    }

    /**
     * 获取博客阅读统计信息
     * @param request
     * @return
     */
    public MessageEntity getReadInfo(HttpServletRequest request) {
        try {
            List<BlogEntity> entities = Lists.newArrayList();
            List<BlogBean> list = blogService.getReadTopFive();
            Integer count = blogService.getReadOther();
            BlogEntity entity1 = new BlogEntity();
            entity1.setTitle("其他");
            entity1.setViews(String.valueOf(count));
            entities.add(entity1);
            for (BlogBean blogBean : list) {
                BlogEntity entity = new BlogEntity();
                entity.setValue(blogBean);
                entities.add(entity);
            }
            return ResultUtil.success(entities);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.fail("系统繁忙、请稍后再试");
        }
    }

    /**
     * 下载博客统计数据pdf文件
     *
     * @param request
     * @param response
     * @return
     */
    public void downPdfFile(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, String> map = new HashMap<>();
            Integer count = blogService.getReadOther();
            List<BlogBean> list = blogService.getReadTopFive();
            map.put("time", DateUtil.dateToStr(new Date(),12));
            map.put("top1",list.get(0).getViews().toString());
            map.put("top2",list.get(1).getViews().toString());
            map.put("top3",list.get(2).getViews().toString());
            map.put("top4",list.get(3).getViews().toString());
            map.put("top5",list.get(4).getViews().toString());
            map.put("other",String.valueOf(count));

            // 设置response参数，可以打开下载页面
            response.reset();
            response.setCharacterEncoding("UTF-8");
            // 定义输出类型
            response.setContentType("application/PDF;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + "BlogInfo"+ (new Date()).getTime() +".pdf");
            ServletOutputStream out = response.getOutputStream();
            PdfUtil pdf = new PdfUtil();
//            String pdfTemplateUrl =  getClass().getClassLoader().getResource("pdf/pdfTest.pdf").getPath();
            String path = this.getClass().getClassLoader().getResource("").getPath();
            //测试
            String path2 = this.getClass().getResource("/").getPath();
            path = path2 + "pdf/pdfTest.pdf";
            pdf.fillTemplate(map, out,path);
            //得到工程的路径：
            System.out.println("得到工程的路径："+System.getProperty("user.dir"));//user.dir指定了当前的路径
            //得到工程目录：
            System.out.println( "得到工程目录："+request.getSession().getServletContext().getRealPath("")); //参数可具体到包名
            //得到IE地址栏地址  request.getRequestURL()
            System.out.println( "得到IE地址栏地址  :"+ request.getRequestURL());
            // 得到相对地址：request.getRequestURI()
            System.out.println( "得到相对地址："+ request.getRequestURI());
//            return ResultUtil.success();
            System.out.println(path);
        } catch (Exception e) {
            e.printStackTrace();
//            return ResultUtil.fail("系统繁忙，请稍后再试");
        }
    }

}
